package data_structure.hash;

import java.util.LinkedList;

/**
 * @Description : 类描述
 * Created by cyd on 2021-03-02 21:15:42
 */
public class MyHashTab {

    private LinkedList<Emp>[] container;

    // 初始化容器
    private void init(int m) {
        container = new LinkedList[m];
        for (int i = 0; i < m; i++) {
            container[i] = new LinkedList<Emp>();
        }
    }

    public MyHashTab(int size) {
        init(size);
    }

    // 哈希（散列）算法
    private int[] hashFunction(int m) {
        if (m < 0) {
            throw new RuntimeException("id不能为负");
        }
        int index = m / 7;
        int indexForArr = m % 7;
        return new int[]{indexForArr, index};
    }

    // 增删查方法
    public void add(Emp emp) {
        int[] ints = hashFunction(emp.getId());
        container[ints[0]].add(emp);
    }

    public Emp find(int id) {
        int[] ints = hashFunction(id);
        return container[ints[0]].get(ints[1]);
    }

    private void delete(int id) {
        int[] ints = hashFunction(id);
        container[ints[0]].remove(ints[1]);
    }

    public void show() {
        for (LinkedList<Emp> list : container) {
            for (Emp emp : list) {
                System.out.println(emp);
            }
            System.out.println("---------------");
        }
    }

    public static void main(String[] args) {
        Emp emp1 = new Emp(1, "1");
        Emp emp2 = new Emp(2, "2");
        Emp emp3 = new Emp(8, "8");
        Emp emp4 = new Emp(15, "15");

        MyHashTab myHashTab = new MyHashTab(7);
        myHashTab.add(emp1);
        myHashTab.add(emp2);
        myHashTab.add(emp3);
        myHashTab.add(emp4);

        Emp emp = myHashTab.find(15);
        System.out.println(emp);

        myHashTab.show();
    }
}
